package com.zyn.es.basic;

import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.get.MultiGetItemResponse;
import org.elasticsearch.action.get.MultiGetRequestBuilder;
import org.elasticsearch.action.get.MultiGetResponse;

/**
 * 批量获取
 * 
 * https://www.elastic.co/guide/en/elasticsearch/client/java-api/current/java-docs-multi-get.html
 * 
 * @author tongyufu
 *
 */
public class MultiGetAPI extends EsClient {

    public static void main(String[] args) {
        new MultiGetAPI().multiGet();
    }

    public void multiGet() {
        super.initClient();
        log.info("================================");
        MultiGetRequestBuilder build = client.prepareMultiGet();
        build.add(INDEX, TYPE, "1"); //获取指定id
        build.add(INDEX, TYPE, "2", "3"); //获取id列表
        build.add("another", "type", "foo"); //获取其他index
        MultiGetResponse responses = build.get();

        for (MultiGetItemResponse item : responses) {
            GetResponse response = item.getResponse();
            //如果index不存在，response为null
            if (response != null && response.isExists()) {
                log.info("==result:" + response.getSourceAsString());
            }
        }
        client.close();
        log.info("================================");
    }

}
